package com.ai.sb.service.impl;

import com.ai.sb.dao.SbSettingMapper;
import com.ai.sb.dao.SbUserMapper;
import com.ai.sb.model.SbRecord;
import com.ai.sb.model.SbSetting;
import com.ai.sb.model.SbUser;
import com.ai.sb.service.SbRecordService;
import com.ai.sb.service.SbUserService;
import com.ai.sb.core.AbstractService;
import com.ai.sb.util.BaseUtil;
import com.ai.sb.util.DES;
import com.ai.sb.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;


/**
 * Created by CodeGenerator on 2018/06/10.
 */
@Service
@Transactional
public class SbUserServiceImpl extends AbstractService<SbUser> implements SbUserService {
    private Logger logger = LoggerFactory.getLogger(SbUserServiceImpl.class);
    @Resource
    private SbUserMapper sbUserMapper;
    @Resource
    private SbSettingMapper sbSettingMapper;

    @Override
    public Result initUser(SbUser sbUser) {
        logger.info("用户初始化，{}",sbUser);
        SbUser qs = new SbUser();
        if(sbUser.getOpenid()!=null){
            logger.info("微信登录");
            qs.setTelNum(sbUser.getTelNum());
        }else if(sbUser.getPhone()!=null){
            logger.info("app登录");
            String decryptDES = null;
            try {
                decryptDES = DES.decryptDES(sbUser.getPhone(), DES.key);
            } catch (Exception e) {
                e.printStackTrace();
            }
            qs.setTelNum(decryptDES.split("=")[1]);
        }else{
            return Result.fail("用户初始化失败");
        }
        logger.info("根据不同渠道获取的telNum:{}",qs);
        SbUser rs = sbUserMapper.selectOne(qs);
        logger.info("根据telNum查询结果：{}",rs);
        if(rs==null){
            //新增用户
            sbUser.setId(BaseUtil.getUUID());
            sbUser.setTelNum(qs.getTelNum());
            logger.info("插入用户,{}",sbUser);
            int i = sbUserMapper.insertSelective(sbUser);
            logger.info("插入结果，{}",i);
            return Result.success(sbUser);
        }else{
            //更新多渠道用户信息
            if(rs.getPhone()==null && sbUser.getPhone()!=null){
                rs.setPhone(sbUser.getPhone());
                logger.info("修改用户phone，{}",rs);
                int i = sbUserMapper.updateByPrimaryKey(rs);
                logger.info("修改结果，{}",i);
            }else if(rs.getOpenid()==null && sbUser.getOpenid()!=null){
                rs.setOpenid(sbUser.getOpenid());
                logger.info("修改用户openid，{}",rs);
                int i = sbUserMapper.updateByPrimaryKey(rs);
                logger.info("修改结果，{}",i);
            }
            return Result.success(rs);
        }
    }

    @Override
    public String getCode() {
        SbSetting sbSetting = sbSettingMapper.selectByPrimaryKey("provinceCode");
        return sbSetting.getSetValue().toString();
    }


}
